﻿<?php
// no direct access
defined( '_JEXEC' ) or die( 'Acces interdit' );

jimport( 'joomla.application.component.model' );

class TournoiModelCreation extends JModel {

	function __construct() {
		parent::__construct();
		
		$mainframe = JFactory::getApplication();
		
		// On ne crée le tournoi en base que si sa description est valorisée
		if (JRequest::getVar('description') != '')
			$this->insertTournoi();
		
		// recupere les parametres de pagination de la session de l utilisateur
		$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', 20, 'int');
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');

		// si limit a change, on ajuste la nouvelle limitstart pour notre liste
		$limitstart = ($limit != 0 ? (floor($limitstart/$limit)*$limit) : 0);
		// on m�morise les nouvelles valeurs dans la session utilisateur
		$this->setState('limitstart', $limitstart);
		$this->setState('limit', $limit);
			
	}

/**
	 * Methode pour construire la requete SQL d'insertion de tournois
	 * @return string de la requete SQL
	 */
	function _buildQueryTournoi() {
		$query = null;
		
		$mainframe = JFactory::getApplication();
		
		// Mail information
		$SiteName 		= $mainframe->getCfg('sitename');
		$MailFrom	 	= $mainframe->getCfg('mailfrom');
		$FromName 		= $mainframe->getCfg('fromname');
		$tzoffset 		= $mainframe->getCfg('offset');		
		
		// informations generales
		$titre = JRequest::getVar('titre');
		
		$description = JRequest::getVar('description');
		//check datdescription --> wipe out code
		$description = strip_tags($description, '<br><br/>');
		//convert the linux \n (Mac \r, Win \r\n) to <br /> linebreaks
		$description = str_replace(array("\r\n", "\r", "\n"), "<br />", $description);
		
		$lieu = JRequest::getVar('lieu');
		
		list($jour,$mois,$annee) = explode('/', JRequest::getVar('datedebut'));
		$datedebut = $annee.'-'.$mois.'-'.$jour;
		$heuredebut = JRequest::getVar('heuredebut');
		
		// information tournois
		$idVariantes = JRequest::getVar('variantes');
		$buyIn = JRequest::getVar('buyIn');
		$tapisDepart = JRequest::getVar('tapisDepart');
		
		$recave = JRequest::getVar('recave');
		if (JRequest::getVar('montantRecave') != '')
			$montantRecave = JRequest::getVar('montantRecave');
		else
			$montantRecave = 0;
		if (JRequest::getVar('jetonRecave') != '')
			$jetonRecave = JRequest::getVar('jetonRecave');
		else
			$jetonRecave = 0;
		
		$addOn = JRequest::getVar('addOn');
		if (JRequest::getVar('montantAddon') != '')
			$montantAddon = JRequest::getVar('montantAddon');
		else
			$montantAddon = 0;
		if (JRequest::getVar('jetonAddon') != '')
			$jetonAddon = JRequest::getVar('jetonAddon');
		else
			$jetonAddon = 0;
			
		$user = & JFactory::getUser();
		$createur = $user->get('id');
		
		$query = "INSERT INTO #__tournois 
					(`idVariantes`, `buyin`, `chips`, `prizepool`, `statut`, `recave`, `recave_montant`, `recave_chips`, `addon`, `addon_montant`, `addon_chips`, `payes`, `dateDebut`, `heure`, `lieu`, `titre`, `description`, `createur`, `idStructures`) 
					VALUES ($idVariantes, $buyIn, $tapisDepart, 0, '', $recave, $montantRecave, $jetonRecave, $addOn, $montantAddon, $jetonAddon, 0, '$datedebut', '$heuredebut', '$lieu', '$titre', '$description', $createur, 1);";
		
		if (JDEBUG) echo "<br />DEBUG : query SQL=".$query."<br><br>";

		return $query;
	}
	
	/**
	 * Methode pour construire la requete SQL d'insertion des participants au tournois
	 * @return string de la requete SQL
	 */
	function _buildQueryParticipants($tournoiId, $joueurId)
	{
		$query = null;
		$query = "INSERT INTO #__joueurs (`idUsers`, `idTournois`, `place`, `gain`, `recave`, `addon`, `statut`) VALUES ($joueurId, $tournoiId,0,0,0,0,0);";
		return $query;
	}
	
	/**
	 * Methode pour récupérer l'email d'un participant au tournois
	 * @return string de la requete SQL
	 */
	function _buildQueryEmail($joueurId)
	{
		$query = null;
		$query = "SELECT email from #__users where id=42";
		return $query;
	}
	
	function _getEmailParticipant($joueurId)
	{ 
		$query = $this->_buildQueryEmail($joueurId);
		$result = $this->_getList($query);
		return @$result;
	}
	
	
  function _getVarianteQuery()
  {
    $db = JFactory::getDBO();
    $id = @$options['id'];
    $query = 'SELECT * FROM #__variantes';
    return $query;
  }

  function getVariantes()
  { 
    $query = $this->_getVarianteQuery();
    $result = $this->_getList($query);
    return @$result;
  }	
  
  function _getStructureQuery()
  {
  	$db = JFactory::getDBO();
  	$id = @$options['id'];
  	$query = 'SELECT * FROM #__structures WHERE idUsers is null';
  	return $query;
  }
  
  function getStructures()
  {
  	$query = $this->_getStructureQuery();
  	$result = $this->_getList($query);
  	return @$result;
  }  
  
  function _getUsersQuery()
  {
    $db = JFactory::getDBO();
    $id = @$options['id'];
    $query = 'SELECT * FROM #__users';
    return $query;
  }

  function getUsers()
  { 
    $query = $this->_getUsersQuery();
    $result = $this->_getList($query);
    return @$result;
  }  

	function insertTournoi()
	{
		$db = JFactory::getDBO();
		$db->setQuery($this->_buildQueryTournoi());
		$result = $db->query();
		
		if ($result != 1)
			echo "ERREUR ! Tournoi non enregistré en base !";
		else
		{
			$tournoi_id = $db->insertid(); // Récupère l'id de l'enregistrement stocké en base
			
			if(($_POST['participants']) && !empty($_POST['participants']))
			{ 
				// manage mailing
				jimport('joomla.utilities.mail');
				$mail = JFactory::getMailer();
				$mail->setSubject( $SiteName.JText::_( 'Nouveau tournoi de poker' ) );
				echo "Subject".$mail->getSubject."<BR>";
				$mail->setSender( array( $MailFrom, $FromName ) );
				echo "Sender".$mail->getSender."<BR>";
				$mailbody = JText::sprintf('Nouveau tournoi dans PTM', 'Check ton PTM mec tu viens de recevoir un nouveau tournoi ca roxe !');
				echo "Body".$mailbody."<BR>";
				$mail->setBody( $mailbody );
				foreach($_POST["participants"] as $joueur_id)
				{
					$db->setQuery($this->_buildQueryParticipants($tournoi_id, $joueur_id));
					$result = $db->query();
					if ($result != 1)
						echo "ERREUR ! Participants non associés au tournoi en base !";
					else
					{
						$query = 'SELECT email FROM #__users where id='.$joueur_id.';';
						$db->setQuery($query);
						$result = $db->query();
						$emailParticipant = $db->loadResult();
						
						$mail->addRecipient($emailParticipant);
						$sent = $mail->Send();
					}
				} 		
			}
		}	
	} 
}
?>
